import {createRouter, createWebHashHistory} from 'vue-router'
import Login from '../views/Login.vue'
import MainBox from '../views/MainBox.vue'
import NotFound from '../views/notfound/NotFound.vue'
import RouteConfig from './config'
import {useRouterStore} from '../store/useRouterStore'
import {useUserStore} from '../store/useUserStore'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const routes = [
    {
        path: "/login",
        name: "login",
        component: Login
    },
    {
        path: "/mainbox",
        name: "mainbox",
        component: MainBox
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

//添加路由 /index 替代了 /mainbox，只写 index 则为 /mainbox/index
// router.addRoute("mainbox",{
//     path:"/index",
//     component:Home
// })

/**
 * 路由拦截
 */
router.beforeEach((to, from, next) => {
    //显示进度条
    NProgress.start();
    const {isGetterRouter} = useRouterStore()
    const {user} = useUserStore()
    if (to.name === "login") {
        next()
    } else {
        if (!user.role) {
            //跳转登录
            next({
                path: "/login"
            })
        } else {
            if (!isGetterRouter) {
                // 确保路由不会重复配置（添加）
                router.removeRoute("mainbox")
                ConfigRouter()
                next({
                    path: to.fullPath
                })
            } else {
                next()
            }
        }
    }
})
router.afterEach(() => {
    //关闭进度条
    NProgress.done();
})
/**
 * 动态配置路由
 * @constructor
 */
const ConfigRouter = () => {
    //创建mainbox
    router.addRoute({
        path: "/mainbox",
        name: "mainbox",
        component: MainBox
    })
    let {changeRouter} = useRouterStore()
    RouteConfig.forEach(item => {
        checkPermission(item.path) && router.addRoute("mainbox", item)
    })
    //重定向
    router.addRoute("mainbox", {
        path: "/",
        redirect: "/index"
    })
    //404
    router.addRoute("mainbox", {
        path: "/:pathMatch(.*)*",
        name: "not found",
        component: NotFound
    })
    changeRouter(true)
}

/**
 * 判断某用户是否具有路由权限
 * @param path
 * @returns {boolean}
 */
const checkPermission = (path) => {
    const {user} = useUserStore()
    return user.role.rights.includes(path)
}
export default router